package com.k8.rpc.util;

import java.nio.charset.StandardCharsets;

/**
 * @Author: k8
 * @CreateTime: 2025-03-20
 * @Version: 1.0
 */
public class HashUtils {
    public static int murmurHash32(String key) {
        byte[] data = key.getBytes(StandardCharsets.UTF_8);
        int length = data.length;
        int seed = 0x9747b28c; // 种子可自定义
        int h1 = seed;
        int c1 = 0xcc9e2d51;
        int c2 = 0x1b873593;

        // 按4字节分组处理
        int i = 0;
        while (i <= length - 4) {
            int k1 = (data[i] & 0xFF)
                    | ((data[i + 1] & 0xFF) << 8)
                    | ((data[i + 2] & 0xFF) << 16)
                    | ((data[i + 3] & 0xFF) << 24);
            k1 *= c1;
            k1 = Integer.rotateLeft(k1, 15);
            k1 *= c2;
            h1 ^= k1;
            h1 = Integer.rotateLeft(h1, 13);
            h1 = h1 * 5 + 0xe6546b64;
            i += 4;
        }

        // 处理剩余字节
        int k1 = 0;
        switch (length & 3) {
            case 3:
                k1 ^= (data[i + 2] & 0xFF) << 16;
            case 2:
                k1 ^= (data[i + 1] & 0xFF) << 8;
            case 1:
                k1 ^= data[i] & 0xFF;
                k1 *= c1;
                k1 = Integer.rotateLeft(k1, 15);
                k1 *= c2;
                h1 ^= k1;
        }

        // 最终混合
        h1 ^= length;
        h1 ^= h1 >>> 16;
        h1 *= 0x85ebca6b;
        h1 ^= h1 >>> 13;
        h1 *= 0xc2b2ae35;
        h1 ^= h1 >>> 16;
        return h1;
    }
}
